//
//  EVEAPI.m
//  iEVEMon
//
//  Created by Scott Guyer on 3/22/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "EVEPortraitService.h"
#import "defs.h"


@implementation EVEPortraitService

@synthesize charID;
@synthesize data;
@synthesize statusCode;

- (id) init
{
	responseDelegate = nil;
	charID = nil;
	data = [[NSMutableData data] retain];

	return self;
}

- (void) doGet:(NSString*)url
{
	NSURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
		cachePolicy:NSURLRequestReloadIgnoringCacheData
		timeoutInterval:5];	
	  
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	if ( connection == nil )
	{
		NSLog(@"%s unable to start connection", __FUNCTION__);
		// TODO: return status
	}
}


// 64x64
- (void) getSmallPortrait:(NSString*)cid respondTo:(id)del usingSelector:(SEL)sel
{
	responseDelegate = del;
	responseSelector = sel;
	
	charID = [cid copy];
	NSString* url = [[NSString alloc] initWithFormat:@"http://img.eve.is/serv.asp?s=64&c=%@", charID];	
	[self doGet:url];
	[url release];
}


// 256x256
- (void) getLargePortrait:(NSString*)cid respondTo:(id)del usingSelector:(SEL)sel
{
	responseDelegate = del;
	responseSelector = sel;
	
	charID = [cid copy];
	NSString* url = [[NSString alloc] initWithFormat:@"http://img.eve.is/serv.asp?s=256&c=%@", charID];	
	[self doGet:url];
	[url release];
}


- (void)connection:(NSURLConnection *)c didReceiveResponse:(NSURLResponse *)response
{
	NSHTTPURLResponse* resp = (NSHTTPURLResponse*)response;	
    [data setLength:0];	
	statusCode = [resp statusCode];
	
	if ( [resp statusCode] != 200 )
	{
		NSLog(@"got response: %d", [resp statusCode]);
		[c cancel];

		[responseDelegate performSelector:responseSelector withObject:self withObject:nil];
	}
}

- (void)connection:(NSURLConnection *)c didReceiveData:(NSData *)d
{
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [data appendData:d];
}

- (void)connection:(NSURLConnection *)c
  didFailWithError:(NSError *)error
{
    [c release];
		
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);

	[responseDelegate performSelector:responseSelector withObject:self withObject:nil];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)c
{
	[c release];
	
    NSLog(@"Succeeded! Received %d bytes of data", [data length]);

	UIImage* img = [[UIImage alloc] initWithData:data];
		
	[responseDelegate performSelector:responseSelector withObject:self withObject:img];

	[img release];
}


- (void)dealloc
{
	NSLog(@"%s 0x%x", __FUNCTION__, self);
	
	WIPE( charID)
	WIPE( data)

	[super dealloc];
}


@end
